﻿package test;

/**
 * 自定义链表
 * */
public class Base6 {
	public static void main(String[] args) {
		JLink jl = new JLink();
		JNode jn1 = new JNode("A");
		JNode jn2 = new JNode("B");
		JNode jn3 = new JNode("C");
		jl.addNode(jn1);
		jl.addNode(jn2);
		jl.addNode(jn3);
		jl.printLink();
		System.out.println("\n"+"Contains A? "+jl.containsNode("A"));
		jl.delNode("A");
		jl.printLink();
	}
}

class JLink {
	JNode root = null;
	//添加节点
	public void addNode(JNode node){
		if(root==null){
			root=node;
		}else{
			root.add(node);
		}
	}
	//删除节点
	public void delNode(String value){
		if(root==null){
			return;
		}else if(!this.containsNode(value)){
			return;
		}else if(root.getValue().equals(value)){
			root = root.getNext();
		}else{
			root.del(root, value);
		}
	}
	//查找节点
	public boolean containsNode(String value){
		if(root==null){
			return false;
		}else{
			return root.contains(value);
		}
	}
	public void printLink(){
		if(root==null){
			System.out.println("null");
		}else{
			root.print();
		}
	}
}

class JNode {
	String value;
	JNode next;

	JNode(String value) {
		this.value = value;
	}

	// 添加节点
	public void add(JNode node) {
		if (this.next == null) {
			this.next = node;
		} else {
			this.next.add(node);
		}
	}

	// 删除节点需要知道当前节点的前一个节点
	public void del(JNode preNode, String value) {
		if (value.equals(this.value)) {
			preNode.next = this.next;
		} else {
			if (this.next != null) {
				this.next.del(this, value);
			}
		}
	}

	// 查找节点
	public boolean contains(String value) {

		if (value.equals(this.value)) {
			return true;
		} else {
			if (this.next != null) {
				return this.next.contains(value);
			} else {
				return false;
			}
		}
	}
	//打印节点
	public void print(){
		System.out.print(this.value+" ");
		if(this.next!=null){
			this.next.print();
		}
	}

	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}

	public JNode getNext() {
		return next;
	}

	public void setNext(JNode next) {
		this.next = next;
	}

}